<template>
  <div>
    <!-- 新增或者修改偏好词 -->
    <el-form
      :model="addForm"
      ref="addFormRef"
      :rules="rules"
      label-position="top"
    >
      <el-form-item prop="typeName" label="类型">
        <el-select
          v-model="addForm.typeName"
          placeholder="请选择类型"
          filterable
        >
          <el-option value="镜片">镜片</el-option>
          <el-option value="镜框">镜框</el-option>
          <el-option value="视训">视训</el-option>
          <el-option value="护理">护理</el-option>
          <el-option value="其他">其他</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="word">
        <el-input
          v-model="addForm.word"
          placeholder="请输入描述"
          ref="wordRef"
          @input="detectionChecked = false"
        />
      </el-form-item>
    </el-form>

    <div class="fixed bottom-2 right-2">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ loading ? "提交中..." : "提交" }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { handleApiResponse } from "@/utils/request.js";
import {
  CreatePreferenceInfo,
  QueryPreferenceInfo,
  UpdatePreferenceInfo,
} from "../../../../../../wailsjs/go/api/CustomerApi";

onMounted(() => {
  if (props.detailForm.id != 0) {
    getDetail();
  }
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  detailForm: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const addFormRef = ref(null);
const addForm = ref({
  id: 0,
  typeName: "",
  word: "",
});

const handleCancel = (val = 0) => {
  addFormRef.value.resetFields();
  emit("handleBack", val);
};

const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    loading.value = true;
    if (props.detailForm.id == 0) {
      handleApiResponse(() => CreatePreferenceInfo(addForm.value)).then(
        (res) => {
          if (res.code == 0) {
            ElMessage.success("新增成功");
            handleCancel(1);
          }
          loading.value = false;
        }
      );
    } else {
      handleApiResponse(() => UpdatePreferenceInfo(addForm.value)).then(
        (res) => {
          if (res.code == 0) {
            ElMessage.success("编辑成功");
            handleCancel(1);
          }
          loading.value = false;
        }
      );
    }
  });
};

async function getDetail() {
  handleApiResponse(() =>
    QueryPreferenceInfo({ id: props.detailForm.id })
  ).then((res) => {
    if (res.code == 0) {
      console.log(res);

      addForm.value = res.data || {};
    }
  });
}

const rules = ref({
  word: [{ required: true, message: "请输入内容" }],
  typeName: [{ required: true, message: "请选择类型" }],
});
</script>

<style scoped lang="scss">
</style>